package edu.neu.swc.skynet.controller;

import com.alibaba.fastjson.JSON;
import edu.neu.swc.skynet.annotation.IgnoreResponseAdvice;
import edu.neu.swc.skynet.service.IJwtService;
import edu.neu.swc.skynet.vo.JwtToken;
import edu.neu.swc.skynet.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <h1>对外暴露授权服务接口</h1>
 * 使用RESTful形式对外暴露授权接口
 */
@RestController
@Slf4j
@RequestMapping("/authority")
public class AuthorityController {

    private final IJwtService iJwtService;

    public AuthorityController(IJwtService iJwtService) {
        this.iJwtService = iJwtService;
    }

    /**
     * <h2>从授权中心获取token</h2>
     * 其实就是登录功能
     * 且返回信息中没有统一相应的包装
     */
    @PostMapping("/token")
    @IgnoreResponseAdvice
    public JwtToken token(@RequestBody UsernameAndPassword usernameAndPassword)
            throws Exception{
        log.info("request to get token with param[{}]", JSON.toJSONString(usernameAndPassword));

        return new JwtToken(iJwtService.generateToken(
                usernameAndPassword.getUsername(),
                usernameAndPassword.getPassword()
        ));
    }

    /**
     * <h2>注册用户</h2>
     * 注册用户并返回当前注册用户的Token及通过授权中心创建用户
     */
    @IgnoreResponseAdvice
    @PostMapping("/register")
    public JwtToken register(@RequestBody UsernameAndPassword usernameAndPassword)
            throws Exception{
        log.info("register user with param:[{}]", JSON.toJSONString(usernameAndPassword));
        return new JwtToken(
                iJwtService.registerUserAndGenerateToken(
                        usernameAndPassword
                ));
    }

}
